package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class PromotionAction extends BaseAction<Promotion> {

	//属性驱动,接受文件
	private File titleImgFile;
	
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	//注入service
	@Autowired
	private PromotionService promotionService;
	

	//保存促销信息,图片上传
	@Action(value="savePromotion",results={@Result(name="success",type="redirect",location="./pages/take_delivery/promotion.html")})
	public String save() throws IOException{
		//获得绝对路径
		String path = ServletActionContext.getServletContext().getRealPath("/upload/");
		System.out.println("绝对路径为:"+path);
		//获取文件名称
		String imgFileName = titleImgFile.getName();
		System.out.println("原文件名为:"+imgFileName);
		//使用uuid修改文件名
		UUID uuid = UUID.randomUUID();
		String ex = imgFileName.substring(imgFileName.lastIndexOf("."));
		String newImgFileName = uuid+ex;
		System.out.println("新文件名为:"+newImgFileName);
		//使用fileutls工具类复制文件;
		FileUtils.copyFile(titleImgFile, new File(path+"/"+newImgFileName));
		//将文件地址存入实体类中(相对路径)
		model.setTitleImg(ServletActionContext.getRequest().getContextPath()+"/upload/"+newImgFileName);
		//调用service层方法保存促销信息
		promotionService.save(model);
		return SUCCESS;
	}
	
	//查询促销信息,显示至bos后台页面
	@Action(value="promotion_pageQuery" ,results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Promotion> pageData = promotionService.pageQuery(pageable);
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
}
